<script setup lang="ts">
const dialogVerifyPhoneShow = ref(false);
const DialogVerifyNewPhoneShow = ref(false);
import { useUserStore } from "~/store/useUser";
import { changeAccount, cancelAccount } from "~/api/user";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { onMounted, ref, watch } from "vue";

const userStore = useUserStore();
const router = useRouter();

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emits = defineEmits(['userInfoUpdated']);

const phone = ref("");

// 初始化手机号
const initPhone = () => {
  // 优先使用 props.userInfo，其次使用 store 的 getUserInfo getter
  phone.value = props.userInfo?.phonenumber || userStore.getUserInfo?.phonenumber || "";
};

onMounted(() => {
  initPhone();
});

// 监听 props.userInfo 的变化
watch(
  () => props.userInfo,
  (newValue) => {
    if (newValue && Object.keys(newValue).length > 0) {
      initPhone();
    }
  },
  { deep: true, immediate: true }
);

// 监听 store 中用户信息的变化（特别是手机号）
watch(
  () => userStore.getUserInfo?.phonenumber,
  (newPhoneNumber) => {
    if (newPhoneNumber) {
      phone.value = newPhoneNumber;
    }
  },
  { immediate: true }
);

const changePhone = () => {
  dialogVerifyPhoneShow.value = true;
};

// 验证旧手机号后进入下一步
const changeNext = (code: string) => {
  // 新接口不需要 oldCode，但保留验证旧手机号的步骤以确保安全性
  dialogVerifyPhoneShow.value = false;
  DialogVerifyNewPhoneShow.value = true;
};

// 验证新手机号, 修改手机号
const newFormData = ref({
  newMobile: "",
  smsCode: "",
});
const submitLoading = ref(false);
const changeNewPhone = async (formData: any) => {
  newFormData.value = formData;
  // 提交数据
  if (!newFormData.value.newMobile || !newFormData.value.smsCode) {
    return ElMessage.warning("请输入手机号和验证码");
  }
  try {
    submitLoading.value = true;
    const result = await changeAccount({
      newMobile: newFormData.value.newMobile,
      smsCode: newFormData.value.smsCode,
    });
    
    if (result.code === 200) {
      ElMessage.success("修改手机号成功");
      // 等待用户信息更新完成
      await userStore.userInfoAction();
      // 立即更新显示的手机号
      phone.value = newFormData.value.newMobile;
      // 通知父组件刷新用户信息
      emits('userInfoUpdated');
      DialogVerifyNewPhoneShow.value = false;
    } else {
      // 处理错误：验证码错误或手机号已被使用
      ElMessage.error(result.msg || "修改手机号失败");
    }
  } catch (error: any) {
    console.log(error);
    ElMessage.error(error?.msg || "修改手机号失败，请重试");
  } finally {
    submitLoading.value = false;
  }
};

// 注销账号
const removeAccountShow = ref(false);
const showRemoveAccount = () => {
  removeAccountShow.value = true;
};

const cancelAccountHandle = async () => {
  try {
    const res = await cancelAccount();
    if (res.code === 200) {
      ElMessage.success(res.msg || "注销账号成功");
      await userStore.logout();
      router.push("/login");
    } else {
      ElMessage.error(res.msg || "注销账号失败");
    }
  } catch (error: any) {
    console.error("注销账号失败:", error);
    ElMessage.error(error?.msg || "注销账号失败，请重试");
  }
};
</script>

<template>
  <div class="acc-info">
    <div class="nickname">
      <span class="label">手机号</span>
      <div>
        <input type="text" v-model="phone" disabled placeholder="请输入更换手机号" />
        <button @click="changePhone">更换手机号</button>
      </div>
    </div>
    <p class="title">注销帐号</p>
    <p class="tips">用户根据需要，注销后账号所有数据将被销毀并不可找回，请谨慎操作。</p>
    <span class="save del" @click="showRemoveAccount">注销账号</span>
  </div>
  <DialogVerifyPhone
    v-if="dialogVerifyPhoneShow"
    :userInfo="props.userInfo"
    @close="dialogVerifyPhoneShow = false"
    @confirm="changeNext"
  />
  <DialogVerifyNewPhone
    v-if="DialogVerifyNewPhoneShow"
    @close="DialogVerifyNewPhoneShow = false"
    @confirm="changeNewPhone"
    :submitLoading="submitLoading"
  />
  <DialogRemoveAccount
    v-if="removeAccountShow"
    @close="removeAccountShow = false"
    @confirm="cancelAccountHandle"
  />
</template>

<style scoped lang="scss">
.acc-info {
  padding: 24px 24px 150px;
}
.title {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 4px;
}
.tips {
  font-size: 12px;
  color: rgba(25, 30, 40, 0.36);
  margin-bottom: 20px;
}
.head {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
  img {
    width: 80px;
    height: 80px;
    margin-right: 10px;
  }
  button {
    width: 92px;
    height: 42px;
    background: #f9fafb;
    border-radius: 6px 6px 6px 6px;
    position: relative;
    border: none;
    color: #191e28;
    input {
      position: absolute;
      opacity: 0;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      cursor: pointer;
    }
  }
}
.nickname {
  display: flex;
  flex-direction: column;
  margin-bottom: 36px;
  .label {
    color: rgba(25, 30, 40, 1);
    font-size: 16px;
    margin-bottom: 12px;
    span {
      color: #ff4f4f;
    }
  }
  & > div {
    display: flex;
  }
  input {
    width: 324px;
    height: 48px;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    padding: 0 12px;
    outline: none;
    margin-right: 12px;
  }
  button {
    width: 120px;
    height: 48px;
    cursor: pointer;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25, 30, 40, 0.16);
    color: #191e28;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    &:hover {
      background: #f9fafb;
      border-color: rgba(29, 191, 115, 0.5);
      color: #1dbf73;
    }
    &:active {
      background: #f5f5f5;
      border-color: #1dbf73;
    }
  }
}
.save {
  display: block;
  width: 160px;
  height: 48px;
  background: #1dbf73;
  border-radius: 8px 8px 8px 8px;
  color: #fff;
  cursor: pointer;
  line-height: 48px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  &.del {
    width: 104px;
    color: #ff4f4f;
    border: 1px solid #ff4f4f;
    background: #fff;
    font-size: 14px;
    user-select: none;
    &:hover {
      background: #ff4f4f;
      color: #fff;
    }
  }
}
</style>
